#include <stdio.h>
#include <stdlib.h>
#include "Stack.h"


int StackInit(Stack* stack) {
	stack->heap = (ElemType*) malloc(STACK_INIT_SIZE * sizeof(ElemType));
	if (stack->heap == NULL) {
		return 1;
	}
	stack->top = 0;
	stack->size = STACK_INIT_SIZE;
	return 0;
}


int StackPush(Stack* stack, ElemType elem) {
	if (stack->top >= stack->size) {
		ElemType* rtn = (ElemType*)
		realloc(stack->heap, (stack->size + STACK_INCREMENT) * sizeof(ElemType));
		if (rtn == NULL) {
			return 1;
		}
		stack->heap = rtn;
		stack->size += STACK_INCREMENT;
	}
	stack->heap[stack->top] = elem;
	stack->top += 1;
	return 0;
}


int StackPop(Stack* stack) {
	if (stack->top <= 0) {
		return 1;
	}
	stack->top -= 1;
	return 0;
}


ElemType StackTop(Stack* stack) {
	return stack->heap[stack->top-1];
}


int StackPrint(Stack* stack) {
	for (int idx = 0; idx < stack->top; idx += 1) {
		printf("%d ", stack->heap[idx]);
	}
	printf("\n");
	return 0;
}


int StackIsEmpty(Stack* stack) {
	return stack->top <= 0;
}


int StackDestroy(Stack* stack) {
	free(stack->heap);
	stack->top = 0;
	stack->size = 0;
}


int mainBk() {
	Stack stack;
	StackInit(&stack);
	for (int x = 1; x <= 8; x += 1) {
		StackPush(&stack, x);
	}
	StackPrint(&stack);
	printf("Top element of stack is %d\n", StackTop(&stack));
	for (int x = 0; x < 5; x += 1) {
		StackPop(&stack);
	}
	StackPrint(&stack);
	for (int x = 0; x < 3; x += 1) {
		StackPop(&stack);
	}
	StackPrint(&stack);
	return 0;
}
